<?php
namespace app\index\controller;
use think\Controller;
use think\Db;//导入模型类
use app\index\model\REST;
use think\Request; //
use app\index\model\Loginaction as Loginaction;

use app\index\controller\Action as Action;

/**
* 
*/
class Login extends Controller
{
	// 首页
	public function index()
	{
		$this->assign('title', '注册');
		return $this->fetch();
	}
	// 手机验证判断是否注册过
	public function yanzheng($phone)
	{
		$data = db('user')->where('phone',$phone)->find();
		if ($data != null) {
			return false;
		}else{
			//随机生成一个验证码
			$code = mt_rand(10000,99999);
			$action = new Action();
			//调用函数:手机号码，替换内容数组，模板ID
			$rec = $action->sendTemplateSMS($phone,array($code,'5'),"1");

			$deadtime = time() + 5*60;
			$data = db('code')->where('phone',$phone)->find();
			if ($data != '') {
				db('code')->where('phone',$phone)->update(['code'=>$code,'deadtime'=>$deadtime]);
			}else{
				db('code')->insert(['phone'=>$phone,'code'=>$code,'deadtime'=>$deadtime]);
			}
			return true;
		}
	}
	// 查询验证码是否正确
	public function yzm()
	{
		$code = input('post.')['code'];
		$phone = input('post.')['phone'];
		$row = db('code')->where('phone',$phone)->find();
		if ($row == '') {
			return 0;
		}else{
			if ($code == $row['code']) {
				if (time() - $row['deadtime'] > 5*60) {
					return 1;
				}else{
					return 2;
				}
			}else{
				return 3;
			}
		}
		
	}
	// 执行注册用户
	public function zhuce()
	{
		$user = input('post.');
		$preg = "/^[1][34578][0-9]{9}$/";
		if (preg_match($preg,$user['phone'])) {	
		}else{
			return $this->error('注册失败',url('login/index'));
			die();
		}
		$uid = mt_rand(11111111,99999999);
		$time = time();
		$data = ['id'=>null,'phone'=>$user['phone'],"pass"=>md5($user["password"])];
		$result = db('user')->insert($data);
		if ($result) {
			$data = db('user')->where('phone',$user['phone'])->find();
			$id = $data['id'];
			$data2 = ['id'=>null,'name'=>$user['name'],'uid'=>$uid,'zctime'=>$time,'userid'=>$id];
			$result2 = db('information')->insert($data2);
			if ($result2) {
				return $this->success('注册成功',url('index/index'));
			}else{
				return $this->error('注册失败',url('login/index'));
			}
		}else{
			return $this->error('注册失败',url('login/index'));
		}
	}

	// 登录
	public function dl()
	{
		$action = new Loginaction();
		$num = $action->register($_POST['phone'],$_POST['pass']);
		return $num;
		
	}
	// 注销
	public function out()
	{
		session('user',null);
		return $this->success('退出成功',url('index/index'));
	}
}
?>